package com.atguigu.serviceucenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.servicebase.exception.GuliException;
import com.atguigu.serviceucenter.entity.UcenterMember;
import com.atguigu.serviceucenter.service.UcenterMemberService;
import com.atguigu.serviceucenter.utils.ConstantPropertiesUtil;
import com.atguigu.serviceucenter.utils.HttpClientUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author JY
 * @create 2021-01-30 15:21
 */
@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    //登陆成功得到用户信息
    //回调url已经固定http://回调地址/api/ucenter/wx/callback
    @GetMapping("callback")
    public String callback(String code,String state){
        //回调地址会带着授权临时票据code和我们定义的state（如这里就是"guli"）

        //访问微信固定地址得到access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl, ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET, code);
        //使用httpclient工具访问固定地址得到数据
        String access = null;
        try {
            access = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            throw new GuliException(20001, "获取access_token失败");
        }
        //得到的数据是json字符串，用Gson工具解析
        Gson gson = new Gson();
        HashMap accessTokenInfo = gson.fromJson(access, HashMap.class);
        String accessToken = (String) accessTokenInfo.get("access_token");
        String openid = (String) accessTokenInfo.get("openid");

        //由于我们在数据库存的是微信唯一标识符openid，先判断当前用用户是否曾经使用过微信登录，如果没用过再接着访问得到信息加入数据库
        UcenterMember member = memberService.getByOpenid(openid);
        if (member == null) {//没用该用户再添加
            //拿着上面得到的access_token和openid访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
            } catch (Exception e) {
                throw new GuliException(20001, "获取用户信息失败");
            }
            //解析json
            HashMap UserInfo = gson.fromJson(resultUserInfo, HashMap.class);
            String nickname = (String) UserInfo.get("nickname");
            String headimgurl = (String) UserInfo.get("headimgurl");

            //向数据库插入一条数据
            member = new UcenterMember();
            member.setNickname(nickname);
            member.setOpenid(openid);
            member.setAvatar(headimgurl);
            memberService.save(member);
        }

        // 生成jwt
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        //因为端口号不同存在蛞蝓问题，cookie不能跨域，所以这里使用url重写

        return "redirect:http://localhost:3000?token="+jwtToken;
    }





    //得到微信扫描登陆二维码
    //根据官方文档，需要重定向到一个官方给的固定连接
    @GetMapping("login")
    public String wxLogin(){
        //微信开放平台授权baseUrl,其中%s和?一样代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //官方中说明请使用urlEncode对链接redirect_uri进行处理
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");//url编码
        } catch (Exception e) {
            e.printStackTrace();
        }
        String guli = String.format(baseUrl, ConstantPropertiesUtil.WX_OPEN_APP_ID, redirectUrl, "guli");
        return "redirect:"+guli;
    }
}
